import { HeroService } from './../hero.service';
import { Hero } from './../hero';
import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute, ParamMap, Router } from '@angular/router';
import { Location } from '@angular/common';
import { switchMap } from 'rxjs';

@Component({
  selector: 'app-hero-detail',
  templateUrl: './hero-detail.component.html',
  styleUrls: ['./hero-detail.component.css']
})
export class HeroDetailComponent implements OnInit {

  hero!: Hero

  constructor(

     private activedRoute: ActivatedRoute,
     private heroService: HeroService,
     private router: Router,

     // location是与浏览器打交道的，用来退回到上一个页面
     private location: Location

  ) { }

  getHero(): void{
     const id = Number(this.activedRoute.snapshot.paramMap.get('id'))
     this.heroService.getHero(id).subscribe(
        hero => this.hero = hero
     )
  }

  ngOnInit(): void {

    this.getHero()
  }

  goBack(hero: Hero): void{
     const heroId = hero ? hero.id : null
     this.router.navigate(['superheroes/',{id: heroId, foo: 'foo'}])
  }

  save(): void{
     if(this.hero){
        this.heroService.updateHero(this.hero).subscribe(() => this.goBack(this.hero))
     }
  }

}
